#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt
import os
import numpy as np
import sys

START = int(sys.argv[1])
STEP = int(sys.argv[2])


def get_faster_wlType(filepath):
    with open(filepath) as f:
        lines = f.readlines()
    baseline_all = -1
    llsm_all = -1
    baseline_read = -1
    llsm_read = -1
    baseline_write = -1
    llsm_write = -1
    for line in lines:
        if "baseline_all" in line:
            baseline_all = float(line.split(' ')[-2])
        elif "llsm_all" in line:
            llsm_all = float(line.split(' ')[-2])
        elif "baseline_read" in line:
            baseline_read = float(line.split(' ')[-2])
        elif "llsm_read" in line:
            llsm_read = float(line.split(' ')[-2])
        elif "baseline_write" in line:
            baseline_write = float(line.split(' ')[-2])
        elif "llsm_write" in line:
            llsm_write = float(line.split(' ')[-2])

    if baseline_all == -1 and baseline_read == -1 and baseline_write == -1:
        fasters = [-1, -1, -1]
    else:
        fasters = [baseline_all/llsm_all, baseline_read/llsm_read, baseline_write/llsm_write]
    return fasters


def get_faster_fileName(filename):
    dataname = filename.split('.')[0]
    realRunpath = "../evaluation/expr_" + dataname + "_trace_realRun_16.txt"
    # allGetpath = "../evaluation/expr_" + dataname + "_trace_allGet_16.txt"
    # allPutpath = "../evaluation/expr_" + dataname + "_trace_allPut_16.txt"

    realRunFaster = get_faster_wlType(realRunpath)
    # allGetFaster = get_faster_wlType(allGetpath)
    # allPutFaster = get_faster_wlType(allPutpath)
    return realRunFaster


dataset_dir = "../data/ebs_segment_io_records/AY283G_2022-01-01_00:00:00_2022-01-02_00:00:00/device/"
with open('./scripts/concurrent_filenames' + str(START) + '_' + str(STEP) + '.txt', 'r') as f:
    lines = f.readlines()
filenames = lines[0]
filenames = filenames.split()

# 下面仅供调试
# print('ERROR ERROR DEBUG ONLY')
# print('ERROR ERROR DEBUG ONLY')
# print('ERROR ERROR DEBUG ONLY')
# filenames = ['111969901601639.csv']

perf_dict = dict()
for filename in filenames:
    # [all read write]的faster其实是，平均后的
    realRunFaster, allGetFaster, allPutFaster = get_faster_fileName(filename)
    perf_dict[filename] = dict({"realRun": realRunFaster, "allGet": allGetFaster, 'allPut': allPutFaster})

keys = perf_dict.keys()
realRunFasters = [perf_dict[key]['realRun'] for key in keys]
allGetFasters = [perf_dict[key]['allGet'] for key in keys]
allPutFasters = [perf_dict[key]['allPut'] for key in keys]

fig, ax = plt.subplots(figsize=(9, 7))
plt.axhline(y=np.array(realRunFasters).mean(), ls='--', color='k', alpha=0.3)  # 与1比较，这里画出1
plt.axhline(y=np.array(allGetFasters).mean(), ls='--', color='b', alpha=0.3)  # 与1比较，这里画出1
plt.axhline(y=np.array(allPutFasters).mean(), ls='--', color='r', alpha=0.3)  # 与1比较，这里画出1

plt.plot(realRunFasters, marker='d', label='realRunFasters', color='k')
plt.plot(allGetFasters, marker='^', label='allGetFasters', color='b')
plt.plot(allPutFasters, marker='v', label='allPutFasters', color='r')

for i in range(len(realRunFasters)):
    plt.text(i, realRunFasters[i], "%.2f" % realRunFasters[i])
for i in range(len(allGetFasters)):
    plt.text(i, allGetFasters[i], "%.2f" % allGetFasters[i])
for i in range(len(allPutFasters)):
    plt.text(i, allPutFasters[i], "%.2f" % allPutFasters[i])

keys4label = [key.split('.')[0][:4] + '..' + key.split('.')[0][-4:] for key in keys]
plt.xticks(range(len(keys)), keys4label, rotation=45)

with open("../evaluation_analyse/num_ops_period.txt") as f:
    line = f.readline()
    num_ops_period = int(line)
plt.title(dataset_dir.split('/')[1] + ": " + str(len(filenames)) + "traces" + "-opsPeriod_" + str(num_ops_period))
plt.legend()
# if not os.path.exists("../evaluation_global/"):
#     os.mkdir("../evaluation_global/")
# plt.ylim(0.6, 1.4)
plt.savefig("../evaluation_global/Mean_Speedup_" + dataset_dir.split('/')[1] + "_opsPeriod_" + str(num_ops_period) + '_' + str(START) + '_' + str(STEP) + '.png')
# plt.show()
plt.close()
